<template>
  <div>
    <el-row>
      <el-button @click="goBack" icon="el-icon-arrow-left">返回</el-button>
    </el-row>
    <div class="taskBtn">
      <el-button type="primary" size="mini" @click="scheduleFormVisable = true" v-if="type =='milestone' && !(detail.taskStatus == 6 || detail.taskStatus == 7) && subTaskData.length == 0">填写进度</el-button>
      <el-button type="primary" size="mini" @click="taskVisable = true" v-if="detail.taskProgress == 1 && type != 'milestone'  && !(detail.taskStatus == 6 || detail.taskStatus == 7)">提交审核</el-button>
      <el-button type="primary" size="mini" @click="goToApprove" v-if="detail.taskProgress == 1 && type == 'milestone' && !(detail.taskStatus == 6 || detail.taskStatus == 7)">提交完成审批</el-button>
    </div>
    <el-tabs v-model="activeName" class="tabs">
      <el-tab-pane label="任务详情" name="first">
        <el-row class="row">
          <el-col :span="6">
            <span class="indent">任务名称</span>
            <span class="text">{{detail.name}}</span>
          </el-col>
          <el-col :span="6">
            <span class="indent">所属项目阶段</span>
            <span class="text">{{detail.stageName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="indent">所属项目</span>
            <span class="text">{{detail.projectName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="indent">进度</span>
            <span class="text">{{(detail.taskProgress * 100).toFixed(0) + '%'}}</span>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="6">
            <span class="indent">开始时间</span>
            <span class="text">{{detail.planStartDate}}</span>
          </el-col>
          <el-col :span="6">
            <span class="indent">完成时间</span>
            <span class="text">{{detail.planEndDate}}</span>
          </el-col>
          <el-col :span="6">
            <span class="indent">状态</span>
            <span class="text">{{detail.statusText}}</span>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="附件" name="second">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>任务详情</span>
            <el-upload
              class="upload"
              :action= uploadUrl
              multiple
              :data="{bizId: $route.query.id, bizType: uploadType}"
              :headers="{
                token: this.token
              }"
              :limit="3"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :on-error="uploadError"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
          <div class="documentList" v-for="(item, index) in fileList" :key="index">
            <div>{{item.name}}</div>
            <div>
              <el-button type="success" size="mini">
                <a :href="item.url" :download="item.name" class="download">下载</a>
              </el-button>
              <el-button type="danger" size="mini" @click="remove(item.id)">删除</el-button>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <div class="taskBtn">
      <el-button type="primary" size="mini" @click="dialogFormVisible = true;isEdit = false;" v-if="type =='milestone' && !(detail.taskStatus == 6 || detail.taskStatus == 7) && (detail.taskProgress == 0 || detail.taskProgress == null) || subTaskData.length != 0">添加子任务</el-button>
      <el-button type="primary" size="mini" @click="scheduleFormVisable = true" v-if="type !='milestone' && !(detail.taskStatus == 6 || detail.taskStatus == 7)">填写进度</el-button>
    </div>
    <el-tabs v-model="active" class="tabs">
      <el-tab-pane label="任务分解" name="first" v-if="type == 'milestone'">
        <el-table style="width: 100%" :data="subTaskData">
          <el-table-column prop="name" label="任务名称" align="center"></el-table-column>
          <el-table-column prop="progress" label="进度" align="center"></el-table-column>
          <el-table-column prop="user" label="负责人" align="center"></el-table-column>
          <el-table-column prop="planStartDate" label="开始时间" align="center"></el-table-column>
          <el-table-column prop="planEndDate" label="完成时间" align="center"></el-table-column>
          <el-table-column prop="statusText" label="状态" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <!-- <el-button size="mini" type="primary" @click="publishSubTask(scope.row)" v-if="!scope.row.taskStatus">发布</el-button> -->
              <el-button size="mini" type="warning" v-if="scope.row.taskStatus == 1" @click="edit(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="deleteSubTask(scope.row)" v-if="scope.row.taskStatus == 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="进度填写记录" name="second">
        <el-table style="width: 100%" :data="scheduleRecord">
          <el-table-column prop="workDescribe" label="工作描述" align="center"></el-table-column>
          <el-table-column prop="progress" label="完成进度" align="center"></el-table-column>
          <el-table-column prop="creator" label="填写人" align="center"></el-table-column>
          <el-table-column prop="createTime" label="填报时间" align="center"></el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="任务审核记录" name="third" v-if="detail.taskType == 2 && (detail.taskStatus == 6 || detail.taskStatus == 7)">
        <el-table style="width: 100%" :data="approveNode[0].userList">
          <el-table-column label="操作" align="center">
            <template>
              <span>任务完成提交</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="描述" align="center"></el-table-column>
          <el-table-column prop="name" label="操作人" align="center"></el-table-column>
          <el-table-column prop="approveText" label="状态" align="center"></el-table-column>
          <el-table-column prop="createTime" label="时间" align="center"></el-table-column>
          <el-table-column>
            <template>
              <el-button type="success" v-if="control" @click="pass" size="mini">审核</el-button>
              <el-button type="danger" @click="rejectVisible = true" v-if="control" size="mini">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="审批流程" name="fouth" v-if="detail.taskType == 1 && (detail.taskStatus == 6 || detail.taskStatus == 7)">
        <div v-for="(item, index) in approveNode" :key="index">
          <div class="documentList">
            <div class="approveNode">{{item.name}}</div>
            <div>
              <div v-for="(user, userIndex) in item.userList" :key="user.id" class="name" @click="reselect(index, user.name, userIndex, item.name)">{{user.name}}</div>
            </div>
            <div class="status">
              <div v-for="user in item.userList" :key="user.id">{{user.approveText}}</div>
            </div>
          </div>
        </div>
        <!-- <el-button type="primary" class="commit" @click="pass" v-if="control">通过</el-button>
        <el-button type="danger" class="commit" @click="rejectVisible = true" v-if="control">驳回</el-button> -->
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="新增子任务" :visible.sync="dialogFormVisible" center>
      <el-form :model="form" ref="form">
        <el-form-item label="任务名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间" :label-width="formLabelWidth">
          <el-date-picker
           v-model="form.endDate" 
           type="date" 
           placeholder="选择日期" 
           style="width: 100%" 
           value-format="yyyy-MM-dd"
           :picker-options="pickerOptions1">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务描述" :label-width="formLabelWidth">
          <el-input v-model="form.description" type="textarea" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="负责人" :label-width="formLabelWidth" v-if="!isEdit">
          <el-button type="text" @click="select">{{user || '选择'}}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubtask">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="进度填写" :visible.sync="scheduleFormVisable" center>
      <el-form :model="scheduleForm" ref="scheduleForm">
        <el-form-item label="时间" :label-width="formLabelWidth">
          <el-date-picker v-model="scheduleForm.date" type="date" placeholder="选择日期" style="width:100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="完成进度" :label-width="formLabelWidth">
          <el-input v-model="scheduleForm.percent" autocomplete="off" class="percent" style="width:100%" @keyup.native="number">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="工作描述" :label-width="formLabelWidth">
          <el-input v-model="scheduleForm.remark" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="scheduleFormVisable = false">取 消</el-button>
        <el-button type="primary" @click="scheduleCommit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="任务完成提交" :visible.sync="taskVisable" center>
      <el-form ref="form" :model="taskFinish">
        <el-form-item label="完成情况描述">
          <el-input v-model="taskFinish.desc" placeholder="请填写任务完成情况描述" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="taskVisable = false">取 消</el-button>
        <el-button type="primary" @click="taskCommit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择负责人" :visible.sync="selectVisible" width="600px">
      <UserSelect :roleId="roleId" :checkList="checkList" v-if="selectVisible" @changeCheckList="changeCheckList" :isSingle="isSingle"></UserSelect>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectVisible = false">取 消</el-button>
        <el-button type="primary" @click="selected">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="rejectVisible" >
      <el-input v-model="rejectText" placeholder="请填写驳回理由"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="reject">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import UserSelect from '@/components/userselect'
import {storage} from '@/utils';
import approveBase from '../base/approveBase';
export default {
  components: {UserSelect},
  mixins: [approveBase],
  data() {
    return {
      detail: '',
      type: 'milestone',
      activeName: "first",
      active: "first",
      dialogFormVisible: false,
      scheduleFormVisable: false,
      taskVisable: false,
      formLabelWidth: "80px",
      form: {
        id: "",
        name: "",
        startDate: "",
        endDate: "",
        description: ""
      },
      subTaskData: [],
      scheduleForm: {
        date: '',
        percent: '',
        remark: ''
      },
      users: [],
      user: '',
      loading: false,
      scheduleRecord: [],
      id: this.$route.query.id,
      taskFinish: {
        desc: ''
      },
      subtaskRecord: [],
      modelId: '',
      pickerOptions: {
        disabledDate: (time) => {
          if (this.form.endDate != "") {
            return time.getTime() > new Date(this.form.endDate).getTime();
          }
        }
      },
      pickerOptions1: {
        disabledDate: (time) => {
          return time.getTime() < new Date(this.form.startDate).getTime();
        }
      },
      roleId: '',
      checkList: [],
      isSingle: true,
      selectVisible: false,
      isEdit: false
    };
  },
  methods: {
    getDetail(type) {
      let params = {
        id: this.id
      }
      this.$store.dispatch('task/getDetail', params).then(res => {
        res.statusText = $status.taskStatus[res.taskStatus];
        // res.planStartDate = res.planStartDate.split(' ')[0];
        // res.planEndDate = res.planEndDate.split(' ')[0];
        this.detail = res;
        if(res.taskStatus == '6') {
          this.status = 'approve';
        }
        if(res.taskType == '2') {
          this.bizType = $conf.bizType['subtask'];
          this.type = "subtask";
          this.active = "second";
          this.modelId = $conf.modelId['subtask'];
        } else {
          this.bizType = $conf.bizType['milestoneTask'];
          this.type = "milestone";
          this.active = "first";  
          this.modelId = $conf.modelId['milestoneTask'];
        }
        if(type == 'first') {
          this.getListProgressInfo();
          this.getUploadFile(this.$route.query.id);
          this.getApproveNode(this.modelId);
          this.getTaskList();
        }
      });
    },
    scheduleCommit() {
      if(!this.scheduleForm.date) {
        return this.$alert('请选择时间');
      }
      if(!this.scheduleForm.percent) {
        return this.$alert('请填写进度');
      }
      if(this.scheduleForm.percent > 100) {
        return this.$alert('进度不能超过100');
      }
      let params = {
        taskId: this.id,
        projectId: this.detail.projectId,
        progress: this.scheduleForm.percent/100,
        workDescribe: this.scheduleForm.remark
      }
      this.$store.dispatch('task/progressCommit', params).then(res => {
        this.showSuccessMessage('填写进度成功');
        this.getDetail();
        this.getListProgressInfo();
        this.scheduleForm = {
          date: '',
          percent: '',
          remark: ''
        }
        this.scheduleFormVisable = false;
      })
    },
    getUser() {
      let params = {
        roleId: '1181464216098000897'
      };
      this.loading = true;
      this.$store.dispatch("project/getRoles", params).then(res => {
        this.loading = false;
        this.users = res;
      });
    },
    addSubtask() {
      if(!this.form.name) {
        return this.$alert('请填写任务名称');
      }
      if(!this.form.startDate) {
        return this.$alert('请选择开始时间');
      }
      if(!this.form.endDate) {
        return this.$alert('请选择结束时间');
      }
      if(!this.user && !this.isEdit) {
        return this.$alert('请选择负责人');
      }
      if(this.isEdit) {
        this.updateSubTask();
      } else {
        let params = {
          milestoneId: this.detail.milestoneId,
          stageName: this.detail.stageName,
          name: this.form.name,
          projectId: this.detail.projectId,
          projectName: this.detail.projectName,
          parentId: this.detail.id,
          planStartDate: this.form.startDate + ' 00:00:00',
          planEndDate: this.form.endDate + ' 00:00:00',
          taskDesc: this.form.description,
          users: this.users.map(item => {
            return {
              userId: item.id,
              userName: item.name
            }
          })
        };
        this.$store.dispatch("task/addSubtask", params).then(res => {
          this.showSuccessMessage('添加子任务成功');
          this.dialogFormVisible = false;
          this.getTaskList();
          this.form = {
            id: "",
            name: "",
            startDate: "",
            endDate: "",
            description: ""
          }
          this.users = [];
          this.user = "";
        })
      }
    },
    getListProgressInfo() {
      let params = {
        taskId: this.id
      } 
      this.$store.dispatch('task/listProgressInfo', params).then(res => {
        this.scheduleRecord = res.map(item => {
          item.progress = (item.progress * 100).toFixed(0) + '%';
          return item;
        });
        console.log(this.scheduleRecord);
      })
    },
    getTaskList() {
      let params ={
        parentId: this.detail.id,
      };
      this.$store.dispatch('task/getTaskList', params).then(res => {
        this.subTaskData = res.map(item => {
          item.progress = item.taskProgress * 100 + '%';
          item.statusText =  $status.taskStatus[item.taskStatus];
          item.user = item.users.map(item => {
            return item.userName;
          }).join(',');
          return item;
        });
      });
    },
    goToApprove() {
      this.$router.push({path: '/task/taskApprove', query: this.detail})
    },
    goBack() {
      this.$router.go(-1);
    },
    deleteSubTask(item) {
      let params = {
        id: item.id
      }
      this.$store.dispatch('task/removeTask', params).then(res => {
        this.showSuccessMessage('删除成功');
        this.getTaskList();
      })
    },
    updateSubTask(item) {
      let params = {
        id: this.form.id,
        planStartDate: this.form.startDate + ' 00:00:00',
        planEndDate: this.form.endDate + ' 00:00:00',
        taskDesc: this.form.description,
        name: this.form.name
      }
      this.$store.dispatch('task/updateTask', params).then(res => {
        this.showSuccessMessage('修改成功');
        this.getTaskList();
        this.form = {
          id: "",
          name: "",
          startDate: "",
          endDate: "",
          description: ""
        }
        this.users = [];
        this.user = "";
        this.dialogFormVisible = false;
      })
    },
    taskCommit() {
      let notifyContent = storage.get('loginInfo').userInfoVO.userName + "提交了《" + this.detail.name + "》子任务完成审批";
      let params = {
        modelId: $conf.modelId['subtask'],
        bizId: this.$route.query.id,
        bizType: $conf.bizType['subtask'],
        notifyContent: notifyContent,
        requestDescribe : this.taskFinish.desc,
        approveNodeList: this.approveNode.map(item => { 
          return {
            approveNodeId: item.id,
            userId: null
          }
        })
      };
      this.$store.dispatch('task/taskApprove', params).then(res => {
        this.showSuccessMessage('申请审批成功');
        this.taskVisable = false;
        this.status = 'approve';
        this.getApproveNode(this.modelId);
        this.getDetail();
      });
    },
    changeCheckList(newCheckList) {
      this.checkList = newCheckList
    },
    select() {
      this.roleId = "1182191961320857601"; 
      this.isSingle = false;
      if(this.users) {
        this.checkList = this.users;
      }
      this.selectVisible = true;
    },
    selected() {
      this.users = this.checkList;
      this.user = this.checkList.map(item => {
        return item.name
      }).join(',');
      this.selectVisible = false;
    },
    edit(row) {
      this.form.name = row.name;
      this.form.startDate = row.planStartDate;
      this.form.endDate = row.planEndDate;
      this.form.id = row.id;
      this.form.description = row.taskDesc;
      this.isEdit = true;
      this.dialogFormVisible = true;
    },
    number(){　　
      this.scheduleForm.percent=this.scheduleForm.percent.replace(/[^\.\d]/g,'');
      this.scheduleForm.percent=this.scheduleForm.percent.replace('.','');
　　}
  },
  mounted() {
    this.id = this.$route.query.id;
    this.uploadType = $conf.uploadType['task'];
    this.approveNode = [{userList: []}];
    this.getDetail('first');
  }
};
</script>
<style lang="less" scoped>
.indent {
  margin-right: 20px;
  font-weight: bold;
}
.row {
  margin-top: 20px;
}
.tabs {
  margin-bottom: 50px;
}
.taskBtn {
  position: absolute;
  right: 20px;
  margin-top: 7px;
  z-index: 1;
}
.documentList {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.download {
  color: #fff;
  text-decoration: none;
}
.manName {
  margin-right: 20px;
}
.upload {
  position: absolute;
  right: 15px;
  top: 10px;
}
.selected {
  margin-right: 20px;
}
.percent {
  width: 220px;
}
.name {
  width: 50px;
  height: 40px;
}
.approveNode {
  width: 150px;
}
.status {
  width: 100px;
  div {
    height: 40px;
  }
}
.commit {
  margin-top: 30px;
}
</style>